<template>
    <div class="map-container">
        <div ref="mapRef" class="map"></div>
        <PlotTools :activeTool="activeTool" @tool-selected="handleToolSelect" />
        <LayerManager :layers="layers" @layer-visibility-changed="handleLayerVisibility" />
        <StyleEditor :visible="styleEditorVisible" :feature="selectedFeature" :feaStyle="featureStyle"
            @confirm="handleStyleConfirm" @delete="handleDeleteFeature" />
        <div id="canvas" class="canvas"></div>
        <div class="yyCls">
            <img src="../assets/images/voice.png" alt="语音录入" @click="startRecording" v-if="showLy" title="点击开始语音录入" />
            <img class="" src="../assets/images/voice_stop.png" alt="停止语音录入" title="停止语音录入" @click="stopRecording"
                v-else />
        </div>
    </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue';
import Map from 'ol/Map';
import View from 'ol/View';
import { fromLonLat } from 'ol/proj';
import PlotService from '../services/plotService';
import EgisService from '../services/egisService';
import PlotTools from './PlotTools.vue';
import LayerManager from './LayerManager.vue';
import StyleEditor from './StyleEditor.vue';
import XiaopaiVoice from 'htht-xiaopai-voice';

const mapRef = ref(null);
const map = ref(null);
const plotService = ref(null);
const activeTool = ref(null);
const showLy = ref(true);
const layers = ref([
    {
        id: 'plot',
        name: '标绘图层',
        visible: true
    }
]);
const styleEditorVisible = ref(false);
const selectedFeature = ref(null);
const featureStyle = ref(null);

const egisService = new EgisService();

// 处理要素点击
const handleFeatureClick = ({ feature, style, isPlot }) => {
    console.log('要素点击:', feature, style, isPlot);
    selectedFeature.value = feature;
    styleEditorVisible.value = isPlot;
    featureStyle.value = style;
};

// 初始化地图
const initMap = async () => {
    const baseLayers = await egisService.initialize();
    console.log('基础图层:', baseLayers);

    map.value = new Map({
        target: mapRef.value,
        view: new View({
            projection: 'EPSG:4490',
            center: fromLonLat([116.3, 39.9], 'EPSG:4490'),
            zoom: 10,
            maxZoom: 20,
            minZoom: 0
        }),
        layers: [...baseLayers]
    });

    plotService.value = new PlotService(map.value, {
        onFeatureClick: handleFeatureClick
    });
    console.log('地图初始化完成');

    // 更新图层列表
    layers.value = [
        {
            id: 'vec',
            name: '矢量底图',
            visible: true,
            layer: baseLayers[0]
        },
        {
            id: 'cva',
            name: '注记图层',
            visible: true,
            layer: baseLayers[1]
        },
        {
            id: 'plot',
            name: '标绘图层',
            visible: true,
            layer: plotService.value.layer
        }
    ];
};

// 处理工具选择
const handleToolSelect = (toolType) => {
    activeTool.value = toolType;
    console.log('选择的工具:', toolType);
    if (toolType) {
        plotService.value.activate(toolType, (feature) => {
            console.log('绘制完成的要素:', feature);
        });
    } else {
        plotService.value.deactivate();
    }
};

// 处理图层可见性变化
const handleLayerVisibility = ({ layerId, visible }) => {
    const layer = layers.value.find(l => l.id === layerId);
    if (layer) {
        layer.visible = visible;
        layer.layer.setVisible(visible);
    }
};

// 处理样式确认
const handleStyleConfirm = (style) => {
    if (selectedFeature.value) {
        if (style.fontFamily) {
            style.fontSize = style.fontSize + 'px';
            style.lineHeight = style.lineHeight + 'px';
            selectedFeature.value.setStyle(style);
        } else {
            plotService.value.Plot.plotUtils.setOpacity(selectedFeature.value, style.opacity);
            plotService.value.Plot.plotUtils.setBorderColor(selectedFeature.value, style.stroke);
            plotService.value.Plot.plotUtils.setBorderWidth(selectedFeature.value, style.width);
            plotService.value.Plot.plotUtils.setBackgroundColor(selectedFeature.value, style.fill);
        }
    }
};

// 处理删除要素
const handleDeleteFeature = () => {
    if (selectedFeature.value) {
        plotService.value.plotDraw.drawLayer.getSource().removeFeature(selectedFeature.value)
        plotService.value.deactivate();
        if (selectedFeature.value.id) {
            const _overlay = map.value.getOverlayById(selectedFeature.value.id);
            if (_overlay) {
                map.value.removeOverlay(_overlay);
            }
        }
        selectedFeature.value = null;
    }
};

//语音识别相关配置
let prevText = '';
const recognition = new XiaopaiVoice({
    container: '#canvas',
    voiceLoad: () => {
        console.log('语音功能加载完成');
    },
    // 以下为可选部分，方便调试
    isInitASR: false, // 是否初始化asr服务
    animationLoad: () => {
        console.log('动画加载完成');
    },
    voiceloadError: (err) => {
        console.error(err);
    },
    animationloadError: (err) => {
        console.error(err);
    },
    asrOption: {
        onResult: (result) => {
            console.log(result);
            const asrText = prevText + result.text;
            if (result.type === 'final') {
                prevText = prevText + result.text;
                console.log('语音识别结果：', prevText);
                showLy.value = true;
            }
            console.log(asrText);
        },
        onStart: () => {
            console.log('开始asr识别');
        },
        onEnd: () => {
            console.log('asr识别结束');
        },
        onError: (err) => {
            console.error(`asr识别错误:${err}`);
        },
    }
});
const startRecording = () => {
    recognition.initASR().then(() => { // isInitASR为false时推荐promise调用，先初始化ASR
        recognition.startRecording();
        showLy.value = false;
    }).catch((error) => {
        console.error(error);
    });
}
const stopRecording = () => {
    recognition.stopRecording();
    showLy.value = true;
}
onMounted(() => {
    initMap();
});

onUnmounted(() => {
    if (map.value) {
        map.value.setTarget(null);
    }
});
</script>

<style scoped>
html,
body {
    margin: 0;
    padding: 0;
    overflow: hidden;
}

.map-container {
    width: 100%;
    height: 100vh;
    position: relative;
    overflow: hidden;
}

.map {
    width: 100%;
    height: 100%;
    position: absolute;
    top: 0;
    left: 0;
}
.canvas {
    width: 720px;
    height: 450px;
    pointer-events: none;
    overflow: hidden;
    position: absolute;
    top:10%;
    left: 30%;
    display: none;
}
.yyCls{
    position: absolute;
    bottom: 30px;
    right: 50px;
    cursor: pointer;
}
</style>